package org.lt.cj.model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import java.util.LinkedList;
import org.lt.cj.config.ServerProperty;

//代理连接类
public class MyDataSource {

    private static MyDataSource instance = new MyDataSource();
    private static String driver = "com.mysql.jdbc.Driver";
    private static String url = "jdbc:mysql://127.0.0.1:3306/tmall";
    private static String user = "root";
    private static String password = "123456";
    private static int initCount = 3; // 初始化连接数
    private static int maxCount = 10; // 最大连接数
    private static int timeout = 100; //连接用完后再次获取连接间隔时间(毫秒)
    int currentCount = 0; // 当前连接数
    // LinkedList方便入列出列操作，性能比ArrayList好
    LinkedList<Connection> connectionsPool = new LinkedList<Connection>();

    public MyDataSource() {
        try {
            for (int i = 0; i < this.initCount; i++) {
                // 把初始化的连接对象存放到链表里面
                this.connectionsPool.addLast(this.createConnection());
                this.currentCount++;
            }
        } catch (SQLException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public static MyDataSource getInstance() {
        return instance;
    }

    //静态内部类在没有新建对象的情况下也可以加载
    static {
        ServerProperty sp = new ServerProperty();
        driver = sp.getValue("driver");
        url = sp.getValue("databaseUrl");
        user = sp.getValue("username");
        password = sp.getValue("password");
        initCount = Integer.parseInt(sp.getValue("initCount"));
        maxCount = Integer.parseInt(sp.getValue("maxCount"));
        timeout = Integer.parseInt(sp.getValue("timeout"));
        sp.closeI();

        try {
            Class.forName(driver);// 加载驱动程序，供调用，只执行一次
        } catch (ClassNotFoundException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    public Connection getConnection() {
        synchronized (connectionsPool) {
            if (this.connectionsPool.size() > 0) // 从链表里面删除头一个连接对象，并返回该连接对象
            {
                return this.connectionsPool.removeFirst();
            }
            if (this.currentCount < maxCount) {
                try {
                    this.currentCount++;
                    return this.createConnection();
                } catch (SQLException ex) {
                    return null;  //无法创建连接，返回空
                }
            }
            return getConnection(timeout);
        }
    }

    /**
     *   根据指定延时取得一个连接
     */
    public synchronized Connection getConnection(long timeout) {
        long startTime = new Date().getTime();
        Connection con = null;
        while ((con = getConnection()) == null) {
            try {
                wait(timeout); //设置等待时间
            } catch (InterruptedException e) {
            }
            if ((new Date().getTime() - startTime) >=  timeout) {
                return null;
            }
        }
        return con;
    }

    // 释放连接，把当前连接加到链表尾,并没有真正关闭
    public void free(Connection conn) {
        this.connectionsPool.addLast(conn);
    }

    // 父类引用指向子类对象，生成一个实现对象供使用
    private Connection createConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }
}
